package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.dao.CustomerSourceDao;
import cc.linker.steplink.crm.dao.LevelDao;
import cc.linker.steplink.crm.domain.WxUserInfo;
import cc.linker.steplink.crm.domain.WxUserInfoDto;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.VipCustomerLogDao;
import cc.linker.steplink.crm.merchanth5.pojo.coupon.CustomerCouponVo;
import cc.linker.steplink.crm.merchanth5.service.*;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantWalletService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.IPersonalCenterService;
import cc.linker.steplink.crm.service.IUserService;
import cc.linker.steplink.crm.service.impl.CreationAwardServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cc.linker.steplink.crm.merchanth5.controller.OverViewInfoController.GUEST;

/**
 * 个人中心接口
 */
@RestController
@Slf4j
@RequestMapping("/personalcenter")
public class PersonalCenterController {

    @Autowired
    private IPersonalCenterService personalCenterService;

    @Autowired
    private CustomerSourceDao customerSourceDao;

    @Autowired
    private VipCustomerLogDao vipCustomerLogDao;

    @Autowired
    private CouponRequest couponRequest;

    @Autowired
    private MallBoomService mallBoomService;

    @Autowired
    private MaiBaoLaService maiBaoLaService;

    @Autowired
    private MerchantWalletService merchantWalletService;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpService httpService;

    private final static String wxAction = "getWeixinUserInfo";

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RequestFilter requestFilter;

    @Value("${casclient.clientHost}")
    private String imgUrl;

    @Value("${wcpay.smsurl}")
    private String smsurl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CreationAwardServiceImpl creationAwardService;

    @Autowired
    private IUserService userService;

    @Autowired
    private CustomerIntegralService customerIntegralService;

    @Autowired
    private VipCustomerLogService vipCustomerLogService;
    @Value("${yzj.orgId}")
    private String yzjOrgId;

    @Autowired
    private RegisterActivityService registerActivityService;

    @Autowired
    private CustomerService customerService;

    /**
     * 个人中心首页
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/home")
    public Object get(HttpServletRequest request) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        redisTemplate.opsForSet().add(GUEST + orgId, customerId);

        //获取用户信息
        Map<String, Object> info = personalCenterService.getCustomerByCid(customerId);
        if (null == info) {
            //如果用户不存在返回空
            Map<String, Object> noUser = new HashMap<>();
            noUser.put("customerAvatar", "");
            noUser.put("customerBalance", "");
            noUser.put("customerId", "");
            noUser.put("customerName", "");
            noUser.put("customerScore", "");
            noUser.put("customerGrowthScore", "");
            noUser.put("customerTotalBalance", "");
            noUser.put("isSaler", 0);
            noUser.put("levelName", "");
            noUser.put("levelOrder", "");
            noUser.put("waitpay", "");
            noUser.put("waitsend", "");
            noUser.put("waittake", "");
            noUser.put("customerType", "normal");
            noUser.put("marketingAccount", "");
            noUser.put("liveAccount", "normal");
            noUser.put("isVip", 0);
            noUser.put("isApp", false);
            noUser.put("isAppVip", false);
            noUser.put("orgId",wxUser.getOrgId());
            return noUser;
        }

        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,orgId);
        info.put("customerScore", integralCustomerInfo.get("customerScore"));
        info.put("customerGrowthScore", integralCustomerInfo.get("customerGrowthScore"));

        //是否已购买会员商品成为会员
        int count = levelDao.selectISsaler(customerId);
        //避免多条记录
        count = count > 0 ? 1 : 0;
        String levelName = "VIP0";
        Integer levelOrder = 0;
        if (!info.containsKey("orgId") || null == info.get("orgId") || info.get("orgId").equals("")) {
            throw new GlobalException(new ResponseException(400, "请先关注公众号"));
        }
        //去开户
        int tlIsOpen = this.openAcsAccount(info, wxUser);
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        List<Map<String, Object>> levels = levelDao.listLevels(map);
        Long customerGrowthScore = Long.valueOf(info.get("customerGrowthScore").toString());
        for (Map<String, Object> level : levels) {
            if ((Long) level.get("levelScore") <= customerGrowthScore) {
                levelOrder = (Integer) level.get("levelOrder");
                levelName = level.get("levelName").toString();
            }
        }
        String bindPhone = wxUser.getBindPhone();
        Map<String, Object> record = personalCenterService.get(customerId, bindPhone, wxUser.getPayMode());
        record.put("customerScore", integralCustomerInfo.get("customerScore"));
        record.put("customerGrowthScore", integralCustomerInfo.get("customerGrowthScore"));
        Long customerBalance = Long.valueOf(info.get("zCustomerBalance").toString());
        Long customerFreeze = Long.valueOf(info.get("zCustomerFreeze").toString());
        Long customerTotalBalance = customerBalance + customerFreeze;

        record.put("customerTotalBalance", NumberUtils.fenToYuan(customerTotalBalance));
        record.put("customerBalance", NumberUtils.fenToYuan(customerBalance));
        record.put("levelName", levelName);
        record.put("levelOrder", levelOrder);
        record.put("isSaler", count);

        Integer isSaler = 0;//是否是联盟商家
        Integer isPromoter = 0;//是否是加盟代理
        Integer isAgent = 0;//是否是推广员
        String agentStatus = "";//推广员状态 0：正常，1：禁用
        Integer isOpenLive = 0; // 是否开通直播
        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getSalerCount(tmpParam);
        if (salerCount > 0) {
            isSaler = 1;
        }
        Integer promoterCount = mallBoomService.getPromoterCount(tmpParam);
        if (promoterCount > 0) {
            isPromoter = 1;
        }
        Integer agentCount = mallBoomService.getAgentCount(tmpParam);
        if (agentCount > 0) {
            isAgent = 1;
            agentStatus = mallBoomService.getAgentCountStatus(customerId);
        }
        Integer openLiveCount = mallBoomService.getStreamByCustomerId(customerId);
        if (openLiveCount > 0) {
            isOpenLive = 1;
        }
        if ("2".equals(info.get("customerSourceChannel"))) {
            WxUserInfoDto wxUserInfoDto;
            Map<String, Object> wxParams = new HashMap<>();
            wxParams.put("action", wxAction);
            wxParams.put("openid", wxUser.getOpenid());
            wxParams.put("token", wxUser.getToken());
            //获取微信用户信息
            Map<String, String> postParam = new HashMap<>();
            postParam.put("Content-Type", "application/json;charset=UTF-8");
            String result = httpService.doPost(systemProperties.getWxpushurl(), com.alibaba.fastjson.JSON.toJSONString(wxParams), postParam);
            wxUserInfoDto = com.alibaba.fastjson.JSON.parseObject(result, WxUserInfoDto.class);
            String subscribe = "0";//Subscribe为0，不关注
            if (wxUserInfoDto.getErrcode().equals("200")) {
                //设置返回值
                WxUserInfo wxUserInfo = wxUserInfoDto.getData();
                subscribe = wxUserInfo.getSubscribe().toString();
                personalCenterService.updateSubscribeByCustomerId(subscribe, customerId);
            }
            record.put("subscribe", subscribe);
        }
        record.put("zIsSaler", isSaler);
        record.put("payMode", wxUser.getPayMode());
        record.put("zIsPromoter", isPromoter);
        record.put("zIsAgent", isAgent);
        record.put("agentStatus", agentStatus);
        record.put("isOpenLive", isOpenLive);
        record.put("customerSourceChannel", info.get("customerSourceChannel"));
        record.put("token", info.get("token"));
        record.put("isVip", wxUser.getIsVip());
        boolean isApp = userService.isApp(orgId);
        record.put("isApp", isApp);
        record.put("orgId",wxUser.getOrgId());
        List vipList = userService.getVipListByCustomerId(customerId);
        record.put("vipList", vipList);
        if (!StringUtils.isEmpty(record.get("marketingAccount"))) {
            record.put("marketingAccount", creationAwardService.getMarketingName(record.get("marketingAccount").toString()));
        }
        record.put("isAppVip", personalCenterService.isAppVip(customerId));
        if(orgId.equals(yzjOrgId)){
            record.put("tlIsOpen",tlIsOpen);
        }else {
            record.put("tlIsOpen",1);
        }
        return record;
    }

    @Async
    protected Integer openAcsAccount(Map customerInfo, WxUser wxUser) {
        int count = 0;
        if(wxUser.getPayMode()==null){
            Integer payMade = personalCenterService.getPayMode(wxUser.getOrgId());
            if(payMade==null){
                payMade =0;
            }
            wxUser.setPayMode(payMade);
        }
        if ((wxUser.getPayMode() == 2 || wxUser.getPayMode() == 3)) {
            String customerId = customerInfo.get("customerId").toString();
            //获取通联开户情况，如果未开户则异步开户
            Map<String, Object> appMemberInfo = maiBaoLaService.getAppCustomerByCid(customerId);
            if (appMemberInfo == null) {
                // 判断用户是否有手机号，
                if (!StringUtils.isEmpty(customerInfo.get("bindPhone"))) {
                    try {
                        // 请求h5用户开户
                        Map<String, Object> map = new HashMap<>();
                        map.put("customerId", customerId);
                        map.put("openId", wxUser.getPayOpenId());
                        map.put("orgId", wxUser.getOrgId());
                        count =  maiBaoLaService.checkCustomerAccount(map, wxUser.getPayMode());
                    } catch (Exception e) {
                        LOGGER.error("个人H5开户失败");
                    }
                }
            }
        }
        return count;
    }

    /**
     * 会员等级
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/level")
    public Object level(HttpServletRequest request) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        Map<String, Object> info = personalCenterService.getCustomerByCid(customerId);

        if (null == info || null == info.get("orgId") || info.get("orgId").equals("")) {
            throw new GlobalException(new ResponseException(400, "请先关注公众号"));
        }
        Map<String, Object> integralCustomerInfo = this.customerIntegralService.getIntegralCustomerInfo(customerId,wxUser.getOrgId());
        info.put("customerScore", integralCustomerInfo.get("customerScore"));
        info.put("customerGrowthScore", integralCustomerInfo.get("customerGrowthScore"));

        String orgId = info.get("orgId").toString();
        Map<String, Object> map = new HashMap<>();

        //获取成长等级
        map.put("orgId", orgId);
        List<Map<String, Object>> levels = levelDao.listLevels(map);
        if(null != levels && levels.size()>0){
            for(Map<String, Object> le:levels){
                if("1".equals(le.get("isCoupon").toString())){
                    //权益卡-礼包-卡券
                    List<Map<String,Object>> vipCoupons = vipCustomerLogDao.getVipCoupons(le.get("levelId").toString());
                    if(null!=vipCoupons && vipCoupons.size()>0){
                        CouponCustomerInfo couponCustomerInfo = requestFilter.getCouponCustomerInfo(request);
                        for(Map<String,Object> vipCoupon:vipCoupons){
                            Map<String, Object> res = (Map) couponRequest.doRequest("coupon-detail", vipCoupon, couponCustomerInfo);
                            vipCoupon.put("cover",res.get("cover"));
                            vipCoupon.put("name",res.get("name"));
                        }
                        le.put("vipCouponList",vipCoupons);
                    }else{
                        le.put("vipCouponList",new ArrayList<>());
                    }
                }else{
                    le.put("vipCouponList",new ArrayList<>());
                }
            }
        }
        map.remove("orgId");
        map.put("levels", levels);

        //获取当前
        Map<String, Object> customerInfo = new HashMap<>();
        Long currentScore = Long.valueOf(info.get("customerScore").toString());
        // 当前成长积分
        Long currentGrowthScore = Long.valueOf(info.get("customerGrowthScore").toString());
        long sub = -1L;
        long tsub = -1L;
        long subNext = -1L;
        for (Map<String, Object> level : levels) {
            List<Map<String, Object>> levelRights = personalCenterService.levelRight((String) level.get("levelId"));
            level.put("levelRights", levelRights);
            if ((Long) level.get("levelScore") <= currentGrowthScore) {
                customerInfo.putAll(level);
                tsub = (Long) level.get("levelScore");
            }
        }
        for (Map<String, Object> level : levels) {
            if ((Long) level.get("levelScore") > currentGrowthScore) {
                sub = (Long) level.get("levelScore") - currentGrowthScore;
                subNext = (Long) level.get("levelScore");
                break;
            }
        }
        if (customerInfo.isEmpty()) {
            customerInfo.put("levelGifts", "");
            customerInfo.put("levelId", "");
            customerInfo.put("orgId", orgId);
            customerInfo.put("giftStatus", 0);
            customerInfo.put("levelBenefits", "");
            customerInfo.put("levelBgimage", "");
            customerInfo.put("levelName", "");
            customerInfo.put("levelOrder", 0);
            customerInfo.put("levelScore", 0);
            customerInfo.put("levelRights", new ArrayList<Map<String, Object>>());
        } else {
            customerInfo.put("levelBgimage", customerInfo.get("levelBgimage").toString());
        }
        customerInfo.put("currentScore", currentScore);
        customerInfo.put("currentGrowthScore", currentGrowthScore);
        customerInfo.put("sub", sub);
        customerInfo.put("tsub", tsub);
        customerInfo.put("subNext", subNext);
        map.put("customerInfo", customerInfo);

        //获取积分规则
        List<Map<String, Object>> scoreRule = personalCenterService.getScoreRule(orgId);
        map.put("scoreRule", scoreRule);

        //获取会员等级权益列表
        for (Map<String, Object> level : levels) {
            if (level.get("levelId").equals(customerInfo.get("levelId"))) {
                level.put("isNow", 1);
            } else {
                level.put("isNow", 0);
            }
        }
//        List<Map<String, Object>> levelRightList = personalCenterService.levelRight(customerInfo.get("levelId").toString());
//        map.put("levelRightList", levelRightList);

        return map;
    }

    /**
     * 获取权益详情
     *
     * @param rightId
     * @return
     */
    @GetMapping("/getlevelrightdetail")
    public Map<String, Object> getLevelRightDetail(int rightId) {
        return personalCenterService.getLevelRightDetail(rightId);
    }


    /**
     * 获取规则说明
     *
     * @param request
     * @return
     */
    @GetMapping("/getrule")
    public Map<String, Object> getRule(HttpServletRequest request, int ruleType) {
        WxUser wxUser = requestFilter.getWxUser(request);
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", wxUser.getOrgId());
        param.put("ruleType", ruleType);
        return personalCenterService.getRule(param);
    }

    /**
     * 积分记录
     *
     * @param request
     * @return
     */
    @GetMapping("/getscorelog")
    public Object getScoreLog(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                              @RequestParam(value = "scoreType", defaultValue = "-1", required = false) int scoreType,
                              HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        Map<String, Object> param = new HashMap<>();
        param.put("customerId", wxUser.getCustomerId());
        param.put("orgId", wxUser.getOrgId());
        param.put("scoreType", scoreType);
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        return personalCenterService.getScoreLog(param);
    }

    /**
     * 会员积分
     *
     * @param
     * @return
     * @throws Exception
     */
    @GetMapping("/listscore")
    public Object listScore(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            HttpServletRequest request) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        Map info = personalCenterService.getCustomerByCid(customerId);

        if (null == info || "".equals(info)) {
            throw new GlobalException(new ResponseException(400, "用户信息不存在"));
        }
        Map<String, String> map = new HashMap();
        map.put("customerId", customerId);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> record = personalCenterService.listScore(map);
        return new PageInfo<>(record);
    }

    /**
     * 账户页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/account")
    public Object account(HttpServletRequest request) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        Map info = personalCenterService.getCustomerByCid(customerId);

        if (null == info || "".equals(info)) {
            throw new GlobalException(new ResponseException(400, "用户信息不存在"));
        }
        Map<String, Object> record = new HashMap();
        //获取绑定手机号
//        String bindPhone = info.get("bindPhone") == null ? "" : info.get("bindPhone").toString();
        String bindPhone = wxUser.getBindPhone();
        //根据customerId获取来源
        String customerSourceChannel = customerSourceDao.getSourceByCid(customerId);

        customerSourceChannel = StringUtils.isEmpty(customerSourceChannel) ?
                (info.get("customerSourceChannel") == null ? "" : info.get("customerSourceChannel").toString())
                : customerSourceChannel;
        record.put("bindPhone", bindPhone);
        record.put("customerSourceChannel", customerSourceChannel);
        record.put("customerName", info.get("customerName"));
        record.put("wxGender", info.get("wxGender"));
        record.put("customerArea", info.get("customerArea"));
        record.put("customerBirth", info.get("customerBirth"));
        LOGGER.info("customerId---->" + customerId + "    customerSourceChannel------>" + customerSourceChannel);
        Map<String, Object> bindInfo = personalCenterService.getBindInfo(customerId);
        LOGGER.info("bindInfo---->" + bindInfo);
        if (bindInfo == null) {
            record.put("bindName", "");
            record.put("bindType", "");
        } else {
            String bindName = bindInfo.get("bindName") == null ? "" : bindInfo.get("bindName").toString();
            String bindType = bindInfo.get("bindType") == null ? "" : bindInfo.get("bindType").toString();
            record.put("bindName", bindName);
            record.put("bindType", bindType);
            LOGGER.info("bindName---->" + bindName + "    bindType------>" + bindType);

        }
        return record;
    }


    /**
     * 修改用户信息
     *
     * @param : customerName 会员姓名
     * @param : wxGender 性别
     * @param : customerArea 地区
     * @param : customerBirth 生日
     * @param : type 修改类型 1.会员姓名 2.性别 3.地区 4.生日
     * @param params
     */
    @PostMapping("/updateUserInfo")
    public void updateUserInfo(@RequestBody Map<String, Object> params,HttpServletRequest request){
        Integer type;
        if(StringUtils.isEmpty(params.get("type"))){
            throw GlobalException.build("参数错误");
        }
        type = Integer.valueOf(params.get("type").toString());
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        params.put("customerId",customerId);
        personalCenterService.updateUserInfo(params,type,wxUser.getOrgId(),wxUser.getGlobalOpenid());
    }

    @PostMapping("/bindphone")
    public List<CustomerCouponVo> bindPhone(@RequestBody Map<String, Object> params,
                                            HttpServletRequest request
    ) throws Exception {

        WxUser wxUser = requestFilter.getWxUser(request);
        Boolean isNewCustomer = StringUtils.isEmpty(wxUser.getBindPhone());
        String token = wxUser.getToken();
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        Integer payMode = wxUser.getPayMode();
        Integer isVip = wxUser.getIsVip();
        // 判断是否是app用户
        Map<String, Object> appMemberInfo = maiBaoLaService.getAppCustomerByCid(customerId);
        boolean appcode = false;
        if (!StringUtils.isEmpty(appMemberInfo) && (payMode == 2 || payMode == 3)) {
            // 判断新老手机号
            int oldPhone = maiBaoLaService.checkOldPhone(params.get("phone").toString(), orgId) > 0 ? 1 : 0;
            String bindPhone = maiBaoLaService.getBindPhoneByCustomerId(customerId);
            if (StringUtils.isEmpty(bindPhone) && oldPhone == 0) {
                // 通联验证码判断 绑定手机号
                Map<String, String> map = new HashMap<>();
                map.put("phone", params.get("phone").toString());
                map.put("verificationCode", params.get("code").toString());
                String alias = "";
                if (payMode == 3) {
                    alias = maiBaoLaService.getAliasByLinker();
                }
                if (payMode == 2) {
                    alias = maiBaoLaService.getAlias(orgId);
                }
                map.put("clintType", alias);
                map.put("customerId", customerId);
                merchantWalletService.tosigncontract(map);
                appcode = true;
            }
        }
        if (!appcode) {
            // 系统 验证码判断
            Map<String, Object> nvps = new HashMap<>();
            nvps.put("businessType", "1020");
            nvps.put("mobilNumber", params.get("phone").toString());
            nvps.put("randomCode", params.get("code").toString());
            String result = smsService.checkVerification(token, nvps);
            Map ret = (Map) JSON.parse(result);
            if ((Integer) ret.get("rt") != 1) {
                throw GlobalException.build("验证码失效");
            }
        }

        // 获取当前登录用户信息
        Map<String, Object> info = personalCenterService.getCustomerByCid(customerId);

        if (null == info) {
            throw GlobalException.build("用户信息不存在");
        }
        params.put("customerId", customerId);
        params.put("openId", wxUser.getOpenid());
        params.put("payOpenId", wxUser.getPayOpenId());
        params.put("token", token);
        params.put("orgId", orgId);
        params.put("bindPhone", info.get("bindPhone"));
        params.put("isVip", isVip);
        params.put("customerSourceChannel", info.get("customerSourceChannel"));
        String key = request.getHeader(Constants.H5_TOKEN_NAME);

        personalCenterService.bindPhone(params, key, wxUser);
        try {
            Map bindUserMap = new HashMap<>();
            bindUserMap.put("openId", wxUser.getOpenid());
            bindUserMap.put("phone", info.get("bindPhone"));
            LOGGER.info("给内容库发消息" + com.alibaba.fastjson.JSON.toJSONString(bindUserMap));
        } catch (Exception e) {
            LOGGER.error("发送失败！");
        }
        if ((payMode == 2 || payMode == 3) && StringUtils.isEmpty(appMemberInfo)) {
            this.openTlAccount(customerId, wxUser.getPayOpenId(), orgId, payMode);
        }
        if (StringUtils.isEmpty(wxUser.getNickname())) {
            //没有昵称加默认昵称
            List<Map<String, Object>> maps = new ArrayList<>();
            Map map = new HashMap();
            map.put("customerName", "");
            map.put("customerPhone", params.get("phone"));
            map.put("customerId", customerId);
            maps.add(map);
            customerService.addCustomerSuffix(maps);
        }
        vipCustomerLogService.growthOpenAccount(customerId, orgId, -1L, null);
        stringRedisTemplate.delete("home:customer_info_" + customerId);
        stringRedisTemplate.delete(CouponRequest.COUPON_LOGIN + customerId);

//        如果是新用户注册才赠送
        if (isNewCustomer) {
            String pid = params.containsKey("shareCustomerId") && !StringUtils.isEmpty(params.get("shareCustomerId")) ? (String) params.get("shareCustomerId") : "";
            //调用任务设置
            this.registerActivityService.registerShareAward(orgId, pid);
            //调用注册有礼赠送接口
            return this.registerActivityService.registerAward(customerId, orgId, pid);

        } else {
            return new ArrayList<>();
        }
    }


    /**
     * @Description：调用通联开户
     * @DateTime：2020/12/30 9:19
     * @Params：
     * @Return：
     */
    @Async
    protected void openTlAccount(String customerId ,String payOpenId,String orgId,Integer payMode) {
        try {
            // 请求h5用户开户
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customerId);
            map.put("openId", payOpenId);
            map.put("orgId", orgId);
            maiBaoLaService.checkCustomerAccount(map, payMode);
        } catch (Exception e) {
            LOGGER.error("1.8个人H5开户失败");
        }
    }


    @PostMapping("/checkcode")
    public void checkCode(@RequestBody Map<String, Object> params,
                          HttpServletRequest request
    ) throws Exception {
        // 验证码判断
        WxUser wxUser = requestFilter.getWxUser(request);
        String token = wxUser.getToken();
        Map<String, Object> nvps = new HashMap<>();
        nvps.put("businessType", "1020");
        nvps.put("mobilNumber", params.get("phone").toString());
        nvps.put("randomCode", params.get("code").toString());
        String result = smsService.checkVerification(token, nvps);


//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        nvps.add(new BasicNameValuePair("businessType", "1020"));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", params.get("phone").toString()));
//        nvps.add(new BasicNameValuePair("randomCode", params.get("code").toString()));
//        String result = ParamSignUtils.callService(smsurl + "/sms/checkVerificationCode", nvps, 0, 0);
        Map ret = (Map) JSON.parse(result);
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("验证码失效");
        }
    }

    /**
    * @Description：获取成长值
    * @DateTime：2020/9/25 10:56
    * @Params：
    * @Return：
    */
    @GetMapping("/getGrowTask")
    public List<Map<String, Object>> getGrowTask(@RequestParam(value = "type", defaultValue = "1", required = false) String type, HttpServletRequest request
    ) throws Exception {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        return personalCenterService.getGrowTaskList(type,orgId);
    }
}
